﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QW.Core.Events
{
    /// <summary>
    /// 事件数据转换器
    /// </summary>
    public static class EventConvert
    {
        /// <summary>
        /// 到数据
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="e"></param>
        /// <returns></returns>
        public static EventData ToEventData<TEvent>(TEvent e)
            where TEvent : class, IEvent
        {
            var type = typeof(TEvent);
            var item = e as IDelayEvent;
            return new EventData
            {
                EventId = item.Identity,
                EventTime = item.EventTime,
                TriggerTime = item.TriggerTime,
                EventName = type.FullName,
                Data = JsonConvert.SerializeObject(item)
            };
        }
        /// <summary>
        /// 到事件
        /// </summary>
        /// <param name="data"></param>
        /// <param name="eventType"></param>
        /// <returns></returns>
        public static object ToEvent(this EventData data, Type eventType)
        {
            var item = JsonConvert.DeserializeObject(data.Data, eventType);
            eventType.GetProperty("Identity").SetValue(item, data.EventId);
            eventType.GetProperty("EventTime").SetValue(item, data.EventTime);
            eventType.GetProperty("TriggerTime").SetValue(item, data.TriggerTime);
            return item;
        }
    }
}
